package com.example.service.impl;

import com.example.entity.Pet;
import com.example.mapper.PetMapper;
import com.example.service.PetService;
import com.example.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class PetServiceImpl implements PetService {
    @Override
    public List<Pet> list(Integer petBreed) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        PetMapper petMapper = sqlSession.getMapper(PetMapper.class);
        List<Pet> pets = petMapper.list(petBreed);
        sqlSession.close();
        return pets;
    }

    @Override
    public int delete(int petId) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        PetMapper petMapper = sqlSession.getMapper(PetMapper.class);
        int result = petMapper.deletePetByPetId(petId);
        sqlSession.close();
        return result;
    }

    @Override
    public Boolean checkPetNameRepeat(String petName) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        PetMapper petMapper = sqlSession.getMapper(PetMapper.class);
        int count = petMapper.checkPetNameRepeat(petName);
        sqlSession.close();
        return count > 0 ? true : false;
    }

    @Override
    public int save(Pet pet) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        PetMapper petMapper = sqlSession.getMapper(PetMapper.class);
        //先查询昵称是否重复，不重复则可以提交
        int count = petMapper.checkPetNameRepeat(pet.getPetName());
        int result;
        if(count == 0){
            result = petMapper.save(pet);
        }else{
            result = -1;
        }
        sqlSession.close();
        return result;
    }
}
